//
//  Home_ViewController.m
//  SlideMenu
//
//  Created by andli on 14-12-11.
//  Copyright (c) 2014年 Aryan Ghassemi. All rights reserved.
//

#import "SHHK_Main_ViewController.h"

#import "MainItem.h"
#import "GDataXMLNode.h"
#import "SHHK_InfoListModel.h"
#import "ItemCell.h"
#import "ItemCell5.h"

@interface SHHK_Main_ViewController ()<UIScrollViewDelegate,MainItemDelegate>
{
    //列表索引
    int pageIndex;
    
    //每页列表数量
    int listPageCount;
    
    NSMutableArray *pageviews;//所有page合集
    
    NSMutableArray *dataArray;
    
    int curpage;//当前页码
    
    NSString *PicInfoID;
    NSString *PicTitle;
}
@property(nonatomic,retain) UIScrollView *myScrollView;
@property(nonatomic,retain) UIImageView  *narrowImageView;
@end

@implementation SHHK_Main_ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"上海虹口";
    
    pageIndex = 0;
    listPageCount = 3;
    
    dataArray = [[NSMutableArray alloc]init];
    pageviews = [[NSMutableArray alloc]init];
    
    
    [SlideNavigationController sharedInstance].enableSwipeGesture = NO;//控制手势
    
    //    [SlideNavigationController sharedInstance].portraitSlideOffset = 60;//默认60
    [self initUI];
    
    curpage = 0;
    [self getData:curpage taskid:1];//请求数据
    
    //    [self setRightBarButtonItemWithImage:@"nav_search" action:@selector(clickSearchButton)];
}


-(void)initUI{
    
    _myScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, AppWidth, AppHeight)];
    
    
    int pagecount = 5;//页数
    
    //设置焦点图控件的一些属性
    _myScrollView.contentSize = CGSizeMake(AppWidth*pagecount, AppHeight);
    _myScrollView.delegate = self;
    
    self.myScrollView.pagingEnabled = YES;
    self.myScrollView.userInteractionEnabled = YES;
    self.myScrollView.bounces = NO;
    self.myScrollView.showsHorizontalScrollIndicator = NO;
    self.myScrollView.showsVerticalScrollIndicator = NO;
    
    for (int i=0; i<pagecount; i++) {
        
        UIView *pageView = [[UIView alloc] initWithFrame:CGRectMake(i*AppWidth,0, AppWidth, AppHeight)];
        [pageviews addObject:pageView];
        
        
        UIImageView *headImage = [[UIImageView alloc]initWithFrame:CGRectMake(0,0, AppWidth, HeadImageH)];
        headImage.tag = i;
        headImage.userInteractionEnabled = YES;
        UITapGestureRecognizer *singleTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickImageView:)];
        [headImage addGestureRecognizer:singleTap1];
        [pageView addSubview:headImage];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10,HeadImageH-35, AppWidth-10, 40)];
        [titleLabel setFont:[UIFont systemFontOfSize:18]];
        [titleLabel setTextColor:[UIColor whiteColor]];
        [pageView addSubview:titleLabel];
        
        UITableView *mTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, headImage.bottom, AppWidth, AppHeight-HeadImageH)];
        mTableView.bounces = NO;
        mTableView.delegate = self;
        mTableView.dataSource = self;
        mTableView.tag = i;
        [pageView addSubview:mTableView];
        
        [self.myScrollView addSubview:pageView];
        [self.view addSubview:_myScrollView];
    }
    
    
    if (IS_IPHONE_5) {
        _narrowImageView = [[UIImageView alloc]initWithFrame:CGRectMake(AppWidth-20,HeadImageH+133, 20, 30)];
    }else{
        _narrowImageView = [[UIImageView alloc]initWithFrame:CGRectMake(AppWidth-15,HeadImageH+92, 15, 30-5)];
    }
    
    [_narrowImageView setImage:[UIImage imageNamed:@"img_shhk_main_nextpage"]];
    [self.view addSubview:_narrowImageView];
}

#pragma mark 图片点击事件
-(void)clickImageView:(UITapGestureRecognizer *)sender{
    
//    NSLog(@"Click ImagView %i",curpage);
//    
//    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
//    [params setObject:PicInfoID forKey:@"InfoID"];
//    [params setObject:@"002"  forKey:@"CateNum"];
//    [params setObject:@"0" forKey:@"IsNeedUrl"];
//    SHHK_XWZX_Detail_ViewController *view = [[SHHK_XWZX_Detail_ViewController alloc]init];
//    view.passParam = params;
//    [self.navigationController pushViewController:view animated:YES];
    
}

#pragma mark 页面滑动
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat pageWidth = scrollView.frame.size.width;
    NSInteger page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    NSLog(@"page=%i",page);
    NSLog(@"curpage=%i",curpage);
    
    
    //只有滑动到下一页后，才重新加载数据
    if(curpage !=page){
        [self getData:page taskid:1];
    }
    
    curpage = page;
    
    if (curpage == 4) {
        //        [self toastMessage:@"最后一页"];
        [_narrowImageView setHidden:YES];
    }else{
        [_narrowImageView setHidden:NO];
    }
    
}

//Click MainItem
-(void)clickMainItem:itemid{
    
    NSLog(@"%@",itemid);
}



#pragma mark - SlideNavigationController Methods -

//显示左菜单
- (BOOL)slideNavigationControllerShouldDisplayLeftMenu
{
    return YES;
}

//显示右菜单
- (BOOL)slideNavigationControllerShouldDisplayRightMenu
{
    return NO;
}

-(void)getData:(int)_index taskid:(int)taskid
{
    [self showMBPHUD];
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:[NSString stringWithFormat:@"%i",_index] forKey:@"CurrentPageIndex"];
    [params setObject:[NSString stringWithFormat:@"%i",listPageCount] forKey:@"PageSize"];
    [params setObject:@"002" forKey:@"CateNum"];
    [params setObject:@"0" forKey:@"IsHeadNews"];
    [params setObject:@"" forKey:@"Title"];
    [self startTask:@"Task_GetInfoListWithPic" withParams:params withTaskId:taskid];
}

-(void)refreshUIWithThreadGuid:(int)taskId andData:(NSObject *)obj{
    [self hideMBPHUD];
    //处理异常信息
    NSMutableArray *arr = (NSMutableArray*)obj;
    if (![[arr objectAtIndex:0]isEqualToString:@"1"]) {
        [self toastMessage:[arr objectAtIndex:1]];
        return;
    }
    
    if (taskId==1) {
        NSString  *bs = [arr objectAtIndex:2];
        
        NSString *xmlstr = [EpointStringUtil getXMLFormatedAttributeBsWithTag:bs xmlTag:@"InfoList"];
        dataArray = [self getLists:xmlstr];
        //刷新tableView
        [[[[pageviews objectAtIndex:curpage]subviews]objectAtIndex:2] reloadData];
        NSString *imageurl = [EpointStringUtil getXMLFormatedAttribute:bs :@"PicUrl"];
        PicInfoID = [EpointStringUtil getXMLFormatedAttribute:bs :@"PicInfoID"];
        PicTitle  = [EpointStringUtil getXMLFormatedAttribute:bs :@"PicTitle"];
        NSURL *imageUrl = [NSURL URLWithString:imageurl];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]];
        UIImageView *imageView = [[[pageviews objectAtIndex:curpage]subviews]objectAtIndex:0];
        UILabel *titleLabel = [[[pageviews objectAtIndex:curpage]subviews]objectAtIndex:1];
        titleLabel.text = PicTitle;
        imageView.image = image;
    }
}

#pragma mark 解析XML
-(NSMutableArray *) getLists:(NSString *)result
{
    NSString *UserArea = [EpointStringUtil getXMLFormatedAttributeBsWithTag:result xmlTag:@"InfoList"];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithXMLString:UserArea  options:0 error:nil];
    GDataXMLElement *rootElement = [doc rootElement];
    NSArray *arrays = [rootElement elementsForName:@"Info"];
    NSMutableArray *dataList = [[NSMutableArray alloc]init];
    for (GDataXMLElement *arr in arrays) {
        SHHK_InfoListModel *f = [[SHHK_InfoListModel alloc]init];
        GDataXMLElement *Infoide = [[arr elementsForName:@"InfoID"] objectAtIndex:0];
        f.InfoID = [Infoide stringValue];
        GDataXMLElement *titleE = [[arr elementsForName:@"Title"] objectAtIndex:0];
        f.Title = [titleE stringValue];
        GDataXMLElement *InfoDate = [[arr elementsForName:@"InfoDate"] objectAtIndex:0];
        f.InfoDate = [InfoDate stringValue];
        GDataXMLElement *IsAttach = [[arr elementsForName:@"IsAttach"] objectAtIndex:0];
        f.IsAttach = [IsAttach stringValue];
        GDataXMLElement *HeadNewsAttachGuid = [[arr elementsForName:@"HeadNewsAttachGuid"] objectAtIndex:0];
        f.HeadNewsAttachGuid = [HeadNewsAttachGuid stringValue];
        GDataXMLElement *ClickTimes = [[arr elementsForName:@"ClickTimes"] objectAtIndex:0];
        f.ClickTimes = [ClickTimes stringValue];
        GDataXMLElement *CategoryName = [[arr elementsForName:@"CategoryName"] objectAtIndex:0];
        f.CategoryName = [CategoryName stringValue];
        [dataList addObject:f];
    }
    return dataList;
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (IS_IPHONE_5) {
        static NSString *WebinfolistItem = @"ItemCell5";
        ItemCell5 *cell = (ItemCell5 *)[tableView dequeueReusableCellWithIdentifier:WebinfolistItem];
        
        if(cell==nil){
            NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"ItemCell5"
                                                        owner:self
                                                      options:nil];
            cell = [nib objectAtIndex:0];
            
        }
        
        if([dataArray count]>0){
            NSUInteger row = [indexPath row];
            SHHK_InfoListModel *info = [dataArray objectAtIndex:row];
            
            cell.infotitleLabel.text = [NSString stringWithFormat:@"%@",info.Title];
            //时间格式2013/2/20 9:00:00
            NSString *infodatestr = info.InfoDate;
            if([infodatestr rangeOfString:@"-"].location !=NSNotFound){
                NSArray *str=[infodatestr componentsSeparatedByString:@" "];
                NSArray *str2=[[str objectAtIndex:0] componentsSeparatedByString:@"-"];
                NSString *timestr= [NSString stringWithFormat:@"%@/%@",[str2 objectAtIndex:1],[str2 objectAtIndex:2]];
                cell.infotimeLabel.text = [NSString stringWithFormat:@"%@ %@",info.CategoryName,timestr];
                
                
            }else{
                cell.infotimeLabel.text = info.InfoDate;
            }
            cell.inforeadnumsLabel.text = info.ClickTimes;
            
        }
        
        return cell;
        
    }else{
        static NSString *WebinfolistItem = @"ItemCell";
        ItemCell *cell = (ItemCell *)[tableView dequeueReusableCellWithIdentifier:WebinfolistItem];
        
        if(cell==nil){
            NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"ItemCell"
                                                        owner:self
                                                      options:nil];
            cell = [nib objectAtIndex:0];
            
        }
        
        if([dataArray count]>0){
            NSUInteger row = [indexPath row];
            SHHK_InfoListModel *info = [dataArray objectAtIndex:row];
            
            cell.infotitleLabel.text = [NSString stringWithFormat:@"%@",info.Title];
            //时间格式2013/2/20 9:00:00
            NSString *infodatestr = info.InfoDate;
            if([infodatestr rangeOfString:@"-"].location !=NSNotFound){
                NSArray *str=[infodatestr componentsSeparatedByString:@" "];
                NSArray *str2=[[str objectAtIndex:0] componentsSeparatedByString:@"-"];
                NSString *timestr= [NSString stringWithFormat:@"%@/%@",[str2 objectAtIndex:1],[str2 objectAtIndex:2]];
                cell.infotimeLabel.text = [NSString stringWithFormat:@"%@ %@",info.CategoryName,timestr];
            }else{
                cell.infotimeLabel.text = info.InfoDate;
            }
            cell.inforeadnumsLabel.text = info.ClickTimes;
            
        }
        
        return cell;
        
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataArray count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    int tableH =(AppHeight-HeadImageH)/3;
    //    NSLog(@"tableH=%i",tableH);
    if(IS_IPHONE_5){
        return 100;
    }
    return 70;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
//    NSLog(@"click table tag %i",tableView.tag);
//    SHHK_InfoListModel *m = [dataArray objectAtIndex:indexPath.row];
//    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
//    [params setObject:m.InfoID forKey:@"InfoID"];
//    [params setObject:@"002"  forKey:@"CateNum"];
//    [params setObject:@"0" forKey:@"IsNeedUrl"];
//    SHHK_XWZX_Detail_ViewController *view = [[SHHK_XWZX_Detail_ViewController alloc]init];
//    view.passParam = params;
//    [self.navigationController pushViewController:view animated:YES];
}

@end


